package com.turing.post.organization.impl;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.ActivateCard;
import com.turing.post.cardmanagement.util.ActivateCardDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.MerchantSecretPolicy;
import com.turing.post.organization.util.MerchantSecretPolicyBusiness;
import com.turing.post.organization.util.MerchantSecretPolicyDao;
import com.turing.post.organization.util.OrganApplicationException;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

@Stateless(mappedName = "organization.impl.MerchantSecretPolicyBusinessImpl")
@Remote
@Local
public class MerchantSecretPolicyBusinessImpl implements
		MerchantSecretPolicyBusiness {

	@EJB(mappedName = "organization.impl.MerchantSecretPolicyDaoImpl")
	private MerchantSecretPolicyDao merchantSecretPolicyDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.ActivateCardDaoImpl")
	private ActivateCardDao activateCardDaoImpl;
	@EJB(mappedName = "	common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;
	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;
	@Override
	public boolean isCardHolderNeedPwd(String merchantNo, String mrchBranchNo,
			Date tranDate, String cardNo, BigInteger amount) {

		ActivateCard ac = activateCardDaoImpl.getActivateCardByCardNo(cardNo);
		if (ac == null)
			return false;

		MerchantSecretPolicy msp = new MerchantSecretPolicy();

		msp.setMerchantNo(merchantNo);
		msp.setMrchBranchNo(mrchBranchNo);
		msp.setStartDate(tranDate);
		msp.setCardFaceId(ac.getCardFaceId());
		msp.setCardClassicId(ac.getCardClassicId());
		msp.setStartCardSeqNo(ac.getCardSeqNo());
		msp.setStartAmount(amount);

		List<MerchantSecretPolicy> msplist = merchantSecretPolicyDaoImpl.getMerchantSecretPolicyByBusiness(msp);
		if (msplist == null || msplist.size() < 1)
			return true;

		MerchantSecretPolicy curmfp = null;
		int curmfpscore = 0;
		int score = 0;

		// 评估策略的优先级,匹配多者优先
		for (MerchantSecretPolicy lmfp : msplist) {
			score = 0;

			// 商户分支机构匹配上+1
			if (PCPSUtil.compareObject(lmfp.getMrchBranchNo(), mrchBranchNo))
				score++;

			// 卡面匹配上+1
			if (PCPSUtil.compareObject(lmfp.getCardFaceId(), ac
					.getCardFaceId()))
				score++;

			// 卡种类匹配上+1
			if (PCPSUtil.compareObject(lmfp.getCardClassicId(), ac
					.getCardClassicId()))
				score++;

			// 卡序号范围完全匹配上+3,匹配上1个+1
			if (!PCPSUtil.isEmpty(lmfp.getStartCardSeqNo())
					&& !PCPSUtil.isEmpty(lmfp.getEndCardSeqNo()))
				score += 3;
			else if (PCPSUtil.isEmpty(lmfp.getStartCardSeqNo())
					&& PCPSUtil.isEmpty(lmfp.getEndCardSeqNo()))
				score += 0;
			else
				score++;

			// 日期范围完全匹配上+3,匹配上1个+1
			if (lmfp.getStartDate() != null && lmfp.getEndDate() != null)
				score += 3;
			else if (lmfp.getStartDate() == null && lmfp.getEndDate() == null)
				score += 0;
			else
				score++;

			// 金额范围完全匹配上+3,匹配上1个+1
			if (BigInteger.ZERO.compareTo(lmfp.getStartAmount()) < 0
					&& BigInteger.ZERO.compareTo(lmfp.getEndAmount()) < 0)
				score += 3;
			else if (BigInteger.ZERO.compareTo(lmfp.getStartAmount()) >= 0
					&& BigInteger.ZERO.compareTo(lmfp.getEndAmount()) >= 0)
				score += 0;
			else
				score++;

			if (score > curmfpscore || curmfp == null) {
				curmfp = lmfp;
				curmfpscore = score;
			}
		}

		return false;
	}
	/**
	 * 新增策略 
	 */
	public void insertMerchantSecretPolicy(PCPSWebInput input,MerchantSecretPolicy merchantSecretPolicy)throws PCPSApplicationException{
		if(input==null || merchantSecretPolicy==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"参数有误!");
		}
		if(input.getOperId()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"用户为空!");
		}
		if(PCPSUtil.isEmpty(merchantSecretPolicy.getMerchantNo())){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户为空!");
		}
		if(merchantSecretPolicy.getStartAmount()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"起始发生额为空!");
		}
		if(merchantSecretPolicy.getEndAmount()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"终止发生额为空!");
		}
		BigInteger mrcSercetPolicyId=commonDaoImpl.getUniqueIntegerKey();
		if(mrcSercetPolicyId==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"得到主键id为空!");
		}
		String StartAmount=String.valueOf(merchantSecretPolicy.getStartAmount().intValue()*100);
		merchantSecretPolicy.setStartAmount(new BigInteger(StartAmount));
		String EndAmount=String.valueOf(merchantSecretPolicy.getEndAmount().intValue()*100);
		merchantSecretPolicy.setMrchSercetPolicyId(new BigInteger(EndAmount));
		merchantSecretPolicy.setCreateOperId(input.getOperId());
		merchantSecretPolicy.setCreateTime(commonDaoImpl.getDatabaseSysTime());
		merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_VALID_AUDITING);
		merchantSecretPolicy.setMrchSercetPolicyId(mrcSercetPolicyId);
		merchantSecretPolicyDaoImpl.insert(merchantSecretPolicy);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(input, SysOperLog.operType_Add,
				"商户无密码交易策略", "商户无密码交易策略");
	}
	/**
	 * 修改策略 
	 */
	public void updateMerchantSecretPolicy(PCPSWebInput input,MerchantSecretPolicy merchantSecretPolicy)throws PCPSApplicationException{
		if(input==null || merchantSecretPolicy==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"参数有误!");
		}
		if(input.getOperId()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"用户为空!");
		}
		if(merchantSecretPolicy.getMrchSercetPolicyId()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户无密码交易策略编号id为空!");
		}
		if(PCPSUtil.isEmpty(merchantSecretPolicy.getMerchantNo())){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户为空!");
		}
		if(merchantSecretPolicy.getStartAmount()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"起始发生额为空!");
		}
		if(merchantSecretPolicy.getEndAmount()==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"终止发生额为空!");
		}
		BigInteger mrcSercetPolicyId=commonDaoImpl.getUniqueIntegerKey();
		if(mrcSercetPolicyId==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"得到主键id为空!");
		}
		MerchantSecretPolicy MerchantSecretPolicy_1=merchantSecretPolicyDaoImpl.getMerchantSecretPolicyByPolicyId(merchantSecretPolicy.getMrchSercetPolicyId());
		if(MerchantSecretPolicy_1==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"策略不存在!");
		}
		if(merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_VALID_AUDITING)){//修改
			if(!input.getOperId().equals(MerchantSecretPolicy_1.getCreateOperId())){
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
						"修改人与创建人不是同一人!");
			}
			merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_VALID_AUDITING);
			merchantSecretPolicy.setCreateTime(commonDaoImpl.getDatabaseSysTime());
		}else if(merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_REFUSE)){//拒绝
			if(input.getOperId().equals(MerchantSecretPolicy_1.getCreateOperId())){
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
						"拒绝人与创建人不能同一人!");
			}
			if(MerchantSecretPolicy_1.getStatus().equals(MerchantSecretPolicy.STATUS_VALID_AUDITING)){//当在生效待审核状态拒绝时，数据库状态修改为，无效				
				merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_INVALID);
				merchantSecretPolicy.setAuthOperId(input.getOperId());
				merchantSecretPolicy.setAuthTime(commonDaoImpl.getDatabaseSysTime());
			}else{//当在无效待审核状态拒绝时，数据库状态修改为，生效				
				merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_VALID);
				merchantSecretPolicy.setAuthOperId(input.getOperId());
				merchantSecretPolicy.setAuthTime(commonDaoImpl.getDatabaseSysTime());
			}
		}else if(merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_VALID)){//生效审核
			if(input.getOperId().equals(MerchantSecretPolicy_1.getCreateOperId())){
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
						"生效审核人与创建人不能同一人!");
			}	
			merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_VALID);
			merchantSecretPolicy.setAuthOperId(input.getOperId());
			merchantSecretPolicy.setAuthTime(commonDaoImpl.getDatabaseSysTime());			
		}else if(merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_INVALID_AUDITING)){//无效待审核申请
			if(input.getOperId().equals(MerchantSecretPolicy_1.getAuthOperId())){
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
						"无效申请人不可为上次审核人!");
			}	
			merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_INVALID_AUDITING);
			merchantSecretPolicy.setAuthOperId(input.getOperId());
			merchantSecretPolicy.setAuthTime(commonDaoImpl.getDatabaseSysTime());				
		}else if(merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_INVALID)){//无效审核
			if(input.getOperId().equals(MerchantSecretPolicy_1.getCreateOperId())){
				throw new OrganApplicationException(
						OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
						"审核无效人与创建人不能同一人!");
			}	
			merchantSecretPolicy.setAuthOperId(input.getOperId());
			merchantSecretPolicy.setStatus(MerchantSecretPolicy.STATUS_INVALID);
			merchantSecretPolicy.setAuthTime(commonDaoImpl.getDatabaseSysTime());				
		}
		
		merchantSecretPolicyDaoImpl.update(merchantSecretPolicy);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(input, SysOperLog.operType_Edit,
				"商户无密码交易策略", "商户无密码交易策略");
	}
	/**
	 * 删除策略 
	 */
	public void deleteMerchantSecretPolicy(PCPSWebInput input,BigInteger feePolicyId)throws PCPSApplicationException{
		if(input==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"用户机构为空!");
		}
		if(feePolicyId==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户手续费收入结算策略id为空!");
		}
		MerchantSecretPolicy merchantSecretPolicy=merchantSecretPolicyDaoImpl.getMerchantSecretPolicyByPolicyId(feePolicyId);
		if(merchantSecretPolicy==null){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户手续费收入结算策略不存在!");
		}
		if(!input.getOperId().equals(merchantSecretPolicy.getCreateOperId())){
			throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"删除人与创建人不是同一人!");
		}
        if(!merchantSecretPolicy.getStatus().equals(MerchantSecretPolicy.STATUS_VALID_AUDITING)){
        	throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"商户手续费收入结算策略不能删除!");
        }
        if(!input.getOperId().equals(merchantSecretPolicy.getCreateOperId())){
        	throw new OrganApplicationException(
					OrganApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
					"你不是创建人不能删除!");
        }
		merchantSecretPolicyDaoImpl.deleteMerchantSecretPolicy(merchantSecretPolicy);
		// 日志记录
		sysOperLogDaoImpl.insertSysOperLogInfo(input, SysOperLog.operType_Delete,
				"商户无密码交易策略", "商户无密码交易策略");
	}
}